package mrms.api.web.controllers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import mrms.api.entity.MeetingEntity;
import mrms.api.entity.MeetingmemberEntity;
import mrms.api.entity.MessageEntity;
import mrms.api.entity.UserEntity;
import mrms.api.repository.MeetingMemberRepository;
import mrms.api.repository.MeetingRepository;
import mrms.api.repository.UserRepository;
import mrms.api.service.MessageService;
import mrms.api.web.dto.AddOrDeleteMeetingMemberDto;
import mrms.api.web.dto.JoinMeetingByInvitationCodeDto;
import mrms.api.web.utils.MessageType;
import mrms.api.web.utils.Result;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author lenchu
 * @date 2019/02/07
 */
@RestController
@AllArgsConstructor
public class MeetingMemberController {
    private final MeetingMemberRepository meetingMemberRepository;
    private final UserRepository userRepository;
    private final MeetingRepository meetingRepository;
    private final MessageService messageService;
    private final ObjectMapper mapper;

    @PostMapping("/meetingmember")
    public Result addMember(@RequestBody @Valid AddOrDeleteMeetingMemberDto meetingMember,
                            @RequestAttribute UserEntity user) {
        MeetingEntity meetingEntity = meetingRepository.findById(meetingMember.getMid());
        meetingEntity.setSponsorDetail(userRepository.findById(meetingEntity.getSponsor()).get());
        try {
            String s = mapper.writeValueAsString(meetingEntity);
            Map map = mapper.readValue(s, Map.class);
            map.put("invitor", user);
            String messageString = mapper.writeValueAsString(map);
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setBeedread(1);
            messageEntity.setContent(messageString);
            messageEntity.setCreatetime(System.currentTimeMillis());
            messageEntity.setType(MessageType.MeetingInvite);
            messageService.newMessage(messageEntity, meetingMember.getMembers().toArray(new String[meetingMember.getMembers().size()]));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        messageService.newMessage(MessageType.MeetingInvite, meetingMember.getMid(),
//        meetingMember.getMembers().toArray(new String[meetingMember.getMembers().size()]));
        return Result.success(meetingMemberRepository.saveAll(meetingMember.getMembers().stream().map(s -> {
            MeetingmemberEntity meetingmemberEntity = new MeetingmemberEntity();
            meetingmemberEntity.setJoined(1);
            meetingmemberEntity.setMid(meetingMember.getMid());
            meetingmemberEntity.setSigntime(0L);
            meetingmemberEntity.setUid(s);
            return meetingmemberEntity;
        }).collect(Collectors.toList())));
    }

    @PutMapping("/meetingmember/{mid}")
    public Result joinIn(@PathVariable Integer mid,
                         @RequestAttribute UserEntity user) {
        MeetingmemberEntity meetingmemberEntity = meetingMemberRepository.findByMidAndUid(mid, user.getId());
        if (meetingmemberEntity != null) {
            meetingmemberEntity.setJoined(0);
            return Result.success(meetingMemberRepository.save(meetingmemberEntity));
        } else {
            return Result.error("无此会议邀请");
        }
    }

    @GetMapping("/meetingmember/{id}")
    public Result getMembers(@PathVariable Integer id) {
        MeetingmemberEntity meetingmemberEntity = new MeetingmemberEntity();
        meetingmemberEntity.setMid(id);
        List<MeetingmemberEntity> all = meetingMemberRepository.findAll(Example.of(meetingmemberEntity));

        for (MeetingmemberEntity mm : all) {
            mm.setUserDetail(userRepository.findById(mm.getUid()).get());
        }

        return Result.success(all);
    }

    @PostMapping("/meetingmember/delete")
    public Result deleteMembers(@RequestBody @Valid AddOrDeleteMeetingMemberDto meetingMember) {
        meetingMemberRepository.deleteAll(meetingMember.getMembers().stream().map(s -> {
            MeetingmemberEntity meetingmemberEntity = new MeetingmemberEntity();
            meetingmemberEntity.setMid(meetingMember.getMid());
            meetingmemberEntity.setUid(s);
            return meetingmemberEntity;
        }).collect(Collectors.toList()));
        messageService.newMessage(MessageType.MemberRemove, meetingMember.getMid(),
                meetingMember.getMembers().toArray(new String[meetingMember.getMembers().size()]));
        return Result.success(null);
    }

    @PostMapping("/meetingmember/invitationCode")
    public Result joinByInvitationCode(@RequestBody @Valid JoinMeetingByInvitationCodeDto jmc,
                                       @RequestAttribute("user") UserEntity user) {
        Optional<MeetingEntity> optionalMeetingEntity = meetingRepository.findById(jmc.getMid());
        if (optionalMeetingEntity.isPresent()) {
            MeetingEntity meetingEntity = optionalMeetingEntity.get();
            if (jmc.getInvitationCode().equals(meetingEntity.getInvitationcode())) {
                MeetingmemberEntity meetingmemberEntity = new MeetingmemberEntity();
                meetingmemberEntity.setMid(jmc.getMid());
                meetingmemberEntity.setUid(user.getId());
                return Result.success(meetingMemberRepository.save(meetingmemberEntity));
            } else {
                return Result.error("邀请码有误");
            }
        } else {
            return Result.error("无此会议");
        }
    }


}
